var express = require('express');
var router = express.Router();
const db = require("../database/db");
var path = require("path");

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
//渲染页面
router.post("/data", function (req, res, next) {
  let id = req.body.id;
  let sql = `SELECT * FROM album WHERE  userid=?`;
  db.query(sql, [id], function (err, result) {
    if (err) {
      console.log(err);
      res.json({ code: 400, msg: "查询失败" ,data: err});
    } else {
      console.log(result);

      res.json({ code: 200, msg: "查询成功", data: result });
    }
  });
});


//添加相册
router.post('/add', function(req, res, next) {
  console.log(req);
  
  try {
    if (!req.files || !req.files.file) {
        return res.status(400).json({ code: 400, msg: "请上传图片" });
    }

    const file = req.files.file;
    const { userid, title } = req.body;
    
    if ( !title) {
        return res.status(400).json({ code: 400, msg: "标题不能为空" });
    }

    const fileExtension = path.extname(file.name);
    const customFileName = Date.now() + '-' + Math.round(Math.random() * 1E9) + fileExtension;
    const uploadPath = path.join(__dirname, '../public/images', customFileName);

    file.mv(uploadPath, (err) => {
        if (err) {
            console.error("文件保存失败:", err);
            return res.status(500).json({ code: 500, msg: "文件保存失败" });
        }

        const cover = `http://127.0.0.1:3001//images/${customFileName}`;
        const sql = `INSERT INTO album (userid, cover, title) VALUES (?, ?, ?)`;
        
        db.query(sql, [userid, cover, title], function (err, result) {
            if (err) {
                console.error("数据库错误:", err);
                return res.status(500).json({ code: 500, msg: "数据库操作失败" });
            }
            
            return res.json({ 
                code: 200, 
                msg: "添加成功", 
                data: {
                    id: result.insertId,
                    cover: cover,
                    title: title
                }
            });
        });
    });
} catch (err) {
    console.error("服务器错误:", err);
    return res.status(500).json({ code: 500, msg: "服务器内部错误" });
}
});
//删除相册
router.post("/delete", function (req, res, next) {
  let { id } = req.body;
  let sql = `DELETE FROM album WHERE id=?`;
  db.query(sql, [id], function (err, result) {
    if (err) {
      console.log(err);
      res.json({
        code: 400,
        msg: "删除失败",
      });
    } else {
      // console.log(result)
      res.json({
        code: 200,
        msg: "删除成功",
        data: result,
      });
    }
  });
});
// 修改相册
router.post("/update", function (req, res) {
    try {
        if (!req.files || !req.files.file) {
            return res.status(400).json({ code: 400, msg: "请上传图片" });
        }

        const file = req.files.file;
        const { id, title } = req.body;
        
        if (!id || !title) {
            return res.status(400).json({ code: 400, msg: "ID和标题不能为空" });
        }

        const fileExtension = path.extname(file.name);
        const customFileName = Date.now() + "-" + Math.round(Math.random() * 1e9) + fileExtension;
        const uploadPath = path.join(__dirname, "../public/images", customFileName);
        
        file.mv(uploadPath, (err) => {
            if (err) {
                console.error("文件保存失败:", err);
                return res.status(500).json({ code: 500, msg: "文件保存失败" });
            }

            const cover = `http://127.0.0.1:3001/images/${customFileName}`;
            const sql = `UPDATE album SET cover=?, title=? WHERE id=?`;
            
            db.query(sql, [cover, title, id], function (err, result) {
                if (err) {
                    console.error("数据库错误:", err);
                    return res.status(500).json({ code: 500, msg: "数据库操作失败" });
                }
                
                if (result.affectedRows === 0) {
                    return res.status(404).json({ code: 404, msg: "未找到要修改的记录" });
                }
                
                return res.json({
                    code: 200,
                    msg: "修改成功",
                    data: {
                        id: id,
                        cover: cover,
                        title: title
                    }
                });
            });
        });
    } catch (err) {
        console.error("服务器错误:", err);
        return res.status(500).json({ code: 500, msg: "服务器内部错误" });
    }
});
module.exports = router;
